package org.fast.project.web.advice;

import static org.fast.project.common.consts.GlobalConst.REQUEST_ID;

import lombok.extern.slf4j.Slf4j;

import org.fast.project.web.exception.GlobalRequestIdNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;


/**
 * @author : lilith·bristol
 * @program : spring-web-archetype-advice
 * @description : 请求上下文工具
 * 用于获取请求流水号 用户身份信息 令牌等
 * @date : 2020-05-03 17:05
 **/
@Component
@Slf4j
public class RequestContextUtil {


    /**
     * 获取请求上下文中的请求流水号
     * 使用@RequestParam @PathVariable注解的Action方法
     * 可以使用此方法获取RequestId
     *
     * @return requestId
     */
    public static String getRequestId() {
        String requestId = "Un traced RequestId";
        try {
            var requestAttr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            var requestIdObj = Optional.ofNullable(requestAttr)
                    .map(ServletRequestAttributes::getRequest)
                    .map(x->x.getAttribute(REQUEST_ID))
                    .orElseThrow(GlobalRequestIdNotFoundException::new);
            if (null != requestIdObj) {
                requestId = (String) requestIdObj;
            }
        } catch (Exception e) {
            log.warn("获取请求流水号异常！", e);
        }
        return requestId;
    }

}
